<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com> <http://www.jxlnxx.com/>
// +----------------------------------------------------------------------

/**
 * API公共库文件
 * 主要定义前台公共函数库
 */

/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map  映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @author 朱亚杰 <zhuyajie@topthink.net>
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 *
 */
function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        foreach ($map as $col=>$pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}
 
/*
 * 连接连接字符串
 */
function tdarr2str($arr)
{
    foreach ($arr as $v) {
        $v = join(",", $v); // 降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    $t = "";
    foreach ($temp as $v) {
        $t .= $v . ",";
    }
    $t = substr($t, 0, - 1);
    return $t;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}

/**
 * 获取列表总行数
 * @param  string  $category 分类ID
 * @param  integer $status   数据状态
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_list_count($category, $status = 1){
    static $count;
    if(!isset($count[$category])){
        $count[$category] = D('Document')->listCount($category, $status);
    }
    return $count[$category];
}

/**
 * 获取段落总数
 * @param  string $id 文档ID
 * @return integer    段落总数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_part_count($id){
    static $count;
    if(!isset($count[$id])){
        $count[$id] = D('Document')->partCount($id);
    }
    return $count[$id];
}

/**
 * 获取导航URL
 * @param  string $url 导航URL
 * @return string      解析或的url
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_nav_url($url){
    switch ($url) {
        case 'http://' === substr($url, 0, 7):
        case '#' === substr($url, 0, 1):
            break;        
        default:
            $url = U($url);
            break;
    }
    return $url;
}

/**
 * 打印接口数据
 * 
 * @param integer $code
 * @param string $message
 * @param array $data
 * @param string $type
 */
function  response($code, $data = array(), $message = '') {
    vendor('response.response');
    
    if (empty($message)) {
        switch ($code) {
            case '1': 
                $message = '操作成功';
                break;
            case '-9':
                $message = '未知错误';
                break;
            case '-94':
                $message = '您还没有登录，请先登录';
                break;
            case '-95':
                $message = 'token为空或已过期';
                break;
            case '-96':
                $message = '你的账号在其他地方已登录，请重新登陆！';
                break;
            case '-97':
                $message = '404错误';
                break;
            case '-98':
                $message = '缺少传递参数';
                break;
            case '-99':
                $message = '请以post方式提交数据';
                break;
            case '-100':
                $message = '你的账号已经在别的地方登陆';
                break;
            default: break;
        }
    }
    
    $type = I('post.format', 'json');
    $response = new Response();
    $response->show($code, $message, $data, $type);
    exit;
}

/**
 * 判断是否缺少参数
 * 
 * @param array $params
 */
function params_exist($params = array()) {
    foreach ($params as $param) {
        !isset($_POST[$param]) && response(-98); 
    }
}

/**
 * 获取REQUEST参数值，并返回数组值
 * 
 * @param array $params
 * @return array
 */
function params_post($params = array()) {
    $result = array();
    
    !is_array($params) && $params = array($params);
    
    foreach ($params as $param) {
        $result[$param] = isset($_POST[$param]) ? $_POST[$param] : '';
    }
    return $result;
}

/**
 * 获取登录Token
 * 
 * @param integer $uid
 * @param string $driver
 * @return string
 */
function addToken($uid, $driver) {
    $encrypt = $uid . NOW_TIME;
    $token = think_ucenter_md5($encrypt, UC_AUTH_KEY);
    
    $data = array(
        'uid' => $uid,
        'driver' => $driver,
        'token' => $token,
        'create_time' => NOW_TIME,
        'deadline' => NOW_TIME + 860000000
    );
    
    $Member_token = M('Member_token');
    
    $Member_token->create($data);
    $Member_token->add();
    
    return $token;
}

/**
 * 验证登录Token
 * 
 * @param string $token
 * @return uid or 打印错误-95
 */
/**
 * @return bool
 * 验证有没有token
 */
function api_login() {
    $token = I('post.token');
    
    $Member_token = M('Member_token');
    $info = $Member_token->where(array('token'=>$token))->find();
    
    return $info ? true  : false;
}

/**
 * @return bool
 * 验证是否过期
 */
function passed_login(){
    $token = I('post.token');
    $Member_token = M('Member_token');
    $info = $Member_token->where(array('token'=>$token, 'deadline' => array('egt', NOW_TIME)))->find();
    return $info ? true : false;
}

/**
 * @return bool
 * 验证是否单点登录
 *
 */
function only_login(){
    $token = I('post.token');
    $Member_token = M('Member_token');
    $info = $Member_token->where(array('token'=>$token,'is_online'=>1, 'deadline' => array('egt', NOW_TIME)))->find();
    return $info ? define('API_UID',$info['uid']) : define('API_UID',false) ;
}



/**
 * 获取随机码
 * 
 * @param number $length
 * @param string $type
 * @return string
 */
function getRandCode($length = 6, $type = 'integer') {
    switch ($type) {
        case 'integer': 
            $chars_array = array(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
            );
            break;
        case 'string':
            $chars_array = array(
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z"
            );
            break;
        default:
            $chars_array = array(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
                "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                "S", "T", "U", "V", "W", "X", "Y", "Z"
            );
    }

    $charsLen = count($chars_array) - 1;

    $outputstr = "";
    for ($i = 0; $i < $length; $i ++) {
        $outputstr .= $chars_array[mt_rand(0, $charsLen)];
    }

    return $outputstr;
}

/**
 *资源文件 url
 */
function get_url($cover_id){
    $path = get_cover($cover_id,'path');
    return $path ? mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")).$path : '';
}

/*
  * 生成订单号
  *
  */
function build_order_no()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);

    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}


function array_remove($data, $key)
{
    if (!array_key_exists($key, $data)) {
        return $data;
    }
    $keys = array_keys($data);
    $index = array_search($key, $keys);
    if ($index !== FALSE) {
        array_splice($data, $index, 1);
    }
    return $data;
}

/**
 * 计算两个时间戳之差
 * @param $begin_time
 * @param $end_time
 * @return array
 */
function timeDiff( $begin_time, $end_time ){
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    Log::info($res);
    return $res;
}